
var fs = require('fs')
var images = require("images");
var ws = require("nodejs-websocket");
console.log("开始建立连接...")

var webconn = null;

var sendWsMsg=(reqInfo,msg)=>{
    if(!webconn) return;
    var replay = {
        reqInfo : reqInfo,
        data : msg
    }
    webconn.sendText(JSON.stringify(replay));
}
global.sendWsMsg = sendWsMsg;

function getResInfo(isSucc,data,message){
    return {
        isSucc : isSucc?true:false,
        data : data,
        message : message,
    }
}
function getImageType(str){
    var reg = /\.(png|jpg|gif|jpeg|webp)$/;
    return str.match(reg)[1];
}
var operInfo={
    getScreen(reqInfo){
        reqInfo.param = reqInfo.param || {};
        const { name} = reqInfo.param;
        var imgpath = "D:/tmp/"+name+".png";
        var resInfo = null
        
        if (!fs.existsSync(imgpath)) {
            resInfo = getResInfo(false,null,"文件不存在")
            sendWsMsg(reqInfo,resInfo)
        }else{
            images(imgpath).size(300).save(imgpath,{quality :100})
            fs.readFile(imgpath,'binary',function(err,data){
                if(err){
                    resInfo = getResInfo(false,null,err.message)
                }else{
                    const buffer = new Buffer(data, 'binary');
                    var imgdata = 'data: image/'+ getImageType(imgpath) +';base64,' + buffer.toString('base64');
                    resInfo = getResInfo(true,imgdata)
                }
                sendWsMsg(reqInfo,resInfo)
            });
        }
    }
}

var server = ws.createServer(function(conn){
    webconn = conn;
    conn.on("text", function (str) {
        try{
            // console.log("收到的信息为:"+str)
            let reqInfo = JSON.parse(str)
            let code = reqInfo.code
            if(code==="init"){
                sendWsMsg(reqInfo,"conn init success")
                return;
            }
            if(operInfo[code]){
                operInfo[code](reqInfo)
            }
        }catch(ex){
            console.log(ex)
        }
    })
    conn.on("close", function (code, reason) {
        console.log("关闭连接")
    });
    conn.on("error", function (code, reason) {
        console.log("异常关闭")
    });
}).listen(19999)
console.log("WebSocket建立完毕")